package com.yanqu.road.server.gameplayer.module.activity.zhanling;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.zhanling.BuyRequestResult;
import com.yanqu.road.entity.activity.zhanling.ZhanLingState;
import com.yanqu.road.entity.activity.zhanling.ZhanLingUserData;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.logic.bussiness.player.activity.ZhanLingActivityBusiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.pb.zhanLingActivity.ZhanLingActivityProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.manger.VipMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.activity.zhanling.ZhanLingActivityMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ：zfr
 * @date ：2021/3/23 17:18
 */
public class ZhanLingActivityModule extends GeneralModule {
    private static Logger logger = LogManager.getLogger(ZhanLingActivityModule.class.getName());
    private Map<Integer, ZhanLingUserData> zhanLingUserDataMap;

    public ZhanLingActivityModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {
        zhanLingUserDataMap = new ConcurrentHashMap<>();
        List<ActivityInfo> zhanLingActivityInfoList = NormalActivityMgr.getZhanLingActivityInfoList();
        List<Integer> activityIdList = new ArrayList<>();
        for (ActivityInfo activityInfo : zhanLingActivityInfoList) {
            activityIdList.add(activityInfo.getActivityId());
        }
        if (zhanLingActivityInfoList.size() > 0) {
            zhanLingUserDataMap = ZhanLingActivityBusiness.getZhanLingUserActivityData(activityIdList, getUserId());
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return true;
    }

    @Override
    public boolean saveData() {
        for (ZhanLingUserData data : zhanLingUserDataMap.values()) {
            if (data.isInsertOption()) {
                ZhanLingActivityBusiness.add(data);
            } else if (data.isUpdateOption()) {
                ZhanLingActivityBusiness.update(data);
            }
        }
        return true;
    }

    @Override
    public void afterLogin() {
        syncActivity();
    }

    /**
     * 推送战令
     * @param activityInfoList
     */
    public void pushGift(List<ActivityInfo> activityInfoList) {
        int userVipLv = VipMgr.getVipLv(player.getUserInfo().getVipExp());
        for (ActivityInfo activity : activityInfoList) {
            //vip限制
            if (userVipLv >= GameConfig.ZHANLING_VIP_LIMIT && !zhanLingUserDataMap.containsKey(activity.getActivityId())) {
                List<Integer> userTriggerGift = ZhanLingActivityMgr.getUserTriggerGift(activity.getActivityId(), player);
                initUserData(activity.getActivityId(), userTriggerGift);
            }
        }
    }

    /**
     * 初始化玩家数据
     * @param activityId
     * @param userTriggerGift
     */
    private void initUserData(int activityId, List<Integer> userTriggerGift) {
        synchronized (zhanLingUserDataMap) {
            if (!zhanLingUserDataMap.containsKey(activityId)) {
                ZhanLingUserData data = new ZhanLingUserData();
                data.setUserId(getUserId());
                data.setActivityId(activityId);
                data.setTriggerGiftList(new ArrayList<>());
                for (Integer id : userTriggerGift) {
                    data.getTriggerGiftList().add(new ZhanLingState(id, false, new Date()));
                }
                data.setTriggerTime(new Date());
                data.setInsertOption();
                zhanLingUserDataMap.put(activityId, data);
            }
        }
    }

    public void syncActivity() {
        if (SystemOpenMgr.systemOpen(player, eSystemId.ZhanLingActivity.getValue())) {
            List<ActivityInfo> activityInfoList = NormalActivityMgr.getZhanLingActivityInfoList();
            if (activityInfoList.size() > 0) {
                pushGift(activityInfoList);
                syncUserDataList();
            }
        }
    }

    /**
     * 是否可以购买礼包
     * @param mallId
     * @return
     */
    public BuyRequestResult isCanBuyGiftBag(int mallId) {
        BuyRequestResult result = new BuyRequestResult();
        result.setMallId(mallId);
        List<ActivityInfo> zhanLingActivityInfoList = NormalActivityMgr.getZhanLingActivityInfoList();
        for (ActivityInfo activityInfo : zhanLingActivityInfoList) {
            ZhanLingUserData zhanLingUserData = zhanLingUserDataMap.get(activityInfo.getActivityId());
            if (zhanLingUserData != null) {
                for (ZhanLingState zhanLingState : zhanLingUserData.getTriggerGiftList()) {
                    if (zhanLingState.getId() == mallId) {
                        result.setActivityId(activityInfo.getActivityId());
                        result.setCanBuy(!zhanLingState.isBuy());
                        return result;
                    }
                }
            }
        }
        result.setCanBuy(false);
        return result;
    }

    /**
     * 购买战令礼包成功
     * @param requestResult
     */
    public void buyMallSuccess(BuyRequestResult requestResult) {
        ZhanLingUserData zhanLingUserData = zhanLingUserDataMap.get(requestResult.getActivityId());
        if (zhanLingUserData != null) {
            for (ZhanLingState zhanLingState : zhanLingUserData.getTriggerGiftList()) {
                if (zhanLingState.getId() == requestResult.getMallId()) {
                    zhanLingState.setBuy(true);
                    zhanLingState.setBuyTime(new Date());
                    zhanLingUserData.setUpdateOption();
                    syncUserDataList();
                    break;
                }
            }
        } else {
            logger.info("active zhanLing gift error, userId:{}, activityId:{}, mallId:{}", getUserId(), requestResult.getActivityId(), requestResult.getMallId());
        }
    }

    /**
     * 是否购买了礼包
     * @param activityId
     * @return
     */
    public boolean isBuyGift(int activityId) {
        ZhanLingUserData zhanLingUserData = zhanLingUserDataMap.get(activityId);
        if (zhanLingUserData != null) {
            List<ZhanLingState> triggerGiftList = zhanLingUserData.getTriggerGiftList();
            for (ZhanLingState zhanLingState : triggerGiftList) {
                if (zhanLingState.isBuy()) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 增加礼包积分
     * @param addScore
     * @param scoreId
     */
    public void addScore(int addScore, int scoreId) {
        if (scoreId == ZhanLingActivityMgr.MeiLiScore) {
            player.notifyListener(eGamePlayerEventType.ZhanLingMeiLiGiftBag.getValue(), addScore);
        } else if (scoreId == ZhanLingActivityMgr.QinMiScore) {
            player.notifyListener(eGamePlayerEventType.ZhanLingQinMiGiftBag.getValue(), addScore);
        } else if (scoreId == ZhanLingActivityMgr.MenKeScore) {
            player.notifyListener(eGamePlayerEventType.ZhanLingMenKeGiftBag.getValue(), addScore);
        } else if (scoreId == ZhanLingActivityMgr.ZhuanSuScore) {
            player.notifyListener(eGamePlayerEventType.ZhanLingZhuanSuGiftBag.getValue(), addScore);
        } else if (scoreId == ZhanLingActivityMgr.YuanBaoScore) {
            player.notifyListener(eGamePlayerEventType.ZhanLingYuanBaoGiftBag.getValue(), addScore);
        }
    }

    private void syncUserDataList() {
        List<ActivityInfo> activityInfoList = NormalActivityMgr.getZhanLingActivityInfoList();
        ZhanLingActivityProto.ZhanLingGiftSync.Builder syncMsg = ZhanLingActivityProto.ZhanLingGiftSync.newBuilder();
        for (ActivityInfo activityInfo : activityInfoList) {
            ZhanLingUserData zhanLingUserData = zhanLingUserDataMap.get(activityInfo.getActivityId());
            if (zhanLingUserData != null) {
                ZhanLingActivityProto.ZhanLingGift.Builder giftTemp = ZhanLingActivityProto.ZhanLingGift.newBuilder();
                giftTemp.setActivityId(activityInfo.getActivityId());
                for (ZhanLingState zhanLingState : zhanLingUserData.getTriggerGiftList()) {
                    ZhanLingActivityProto.GiftStateTemp.Builder giftState = ZhanLingActivityProto.GiftStateTemp.newBuilder();
                    giftState.setMallId(zhanLingState.getId());
                    giftState.setIsBuy(zhanLingState.isBuy());
                    giftTemp.addGift(giftState);
                }
                syncMsg.addGift(giftTemp);
            }
        }
        player.sendPacket(ClientProtocol.U_ACTIVITY_ZHANLING_GIFT_SYNC, syncMsg);
    }
}
